// 节流函数
export function throttle(fn, delay = 500) {
  let timer = null
  return function (...args) {
    if (timer) return
    timer = setTimeout(() => {
      fn.apply(this, args)
      timer = null
    }, delay)
  }
}

//防抖函数
export function debounce(fn, delay = 500) {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 播放网易云的音乐
export function getSongPlayUrl(id) {
  return `https://music.163.com/song/media/outer/url?id=${id}.mp3`
}

// 格式话时间 将秒转换成 mm:ss
export function formatTime(time) {
  if (!time && time !== 0) return '00:00'
  return new Date(time * 1000).toISOString().substr(14, 5)
}

// 格式话时间 将mm:ss转换成秒
export function formatTimeToSeconds(time) {
  return time.split(':').reduce((acc, cur) => acc * 60 + +cur)
}

// 将颜色转变为rgba
export function toRGBA(color, opacity) {
  const tempDiv = document.createElement('div')
  tempDiv.style.color = color
  document.body.appendChild(tempDiv)
  const computedColor = window.getComputedStyle(tempDiv).color
  document.body.removeChild(tempDiv)
  const values = computedColor.match(/\d+/g)
  if (!values || values.length < 3) {
    throw new Error('无法解析颜色值: ' + color)
  }
  const alpha = Math.min(1, Math.max(0, opacity))
  return `rgba(${values[0]}, ${values[1]}, ${values[2]}, ${alpha})`
}
